$NG.AllReady(function (page, { useDataIndexChange, useUpdateRow, useUpdateRows, useValuesChange, useClick }) {
  // 编辑页面逻辑
  const mstform = $NG.getCmpApi("p_form_owner_rec_apply_m");
  const grid1 = $NG.getCmpApi("p_form_owner_rec_apply_d1");
  const grid2 = $NG.getCmpApi("p_form_owner_rec_apply_d2");
  const grid3 = $NG.getCmpApi("p_form_owner_rec_apply_d3");
  const grid4 = $NG.getCmpApi("p_form_owner_rec_apply_d4");

  // u_dept;
  var dtoolbar1 = $NG.getCmpApi("toolbar_p_form_owner_rec_apply_d1");
  dtoolbar1.insert({
    id: "add",
    text: "物料信息",
    iconCls: "icon-New",
  });
  useClick(async function ({ args }) {
    planadd();
  }, "add");

  function planadd() {
    $NG.external
      .openNGHelp({
        type: "NGMultipleHelp", //NGMultipleHelp
        helpId: "itemdataIdToNo_copy", //帮助id
       // valueField: "phid_itemdata",
        // labelField: "itemno", //显示字段
        // clientSqlFilter: {
        // 	bill_no: mstform.getValues().u_rkdbm_EXName,
        // 	phid_transno: 1,
        // },
      })
      .then((data) => {
        //根据字段名称新增引入每一行
        console.log(data, "data111111");
        try {
          if (Array.isArray(data) && data.length > 0) {
            var gridArr = [];
            for (var i = 0; i < data.length; i++) {
              console.log(data[i], "row1数据");
              var gridObj = {};
              //资源品类
              gridObj.u_wl_no = data[i].origin.phid_itemdata;
              gridObj.u_wl_no_EXName = data[i].origin.ItemNo;
              gridObj.u_wl_name = data[i].origin.ItemName;
              gridArr.push(gridObj);
            }

            console.log("planadd gridArr:");
            console.log(gridArr);
            grid1.addRows(gridArr);
            //  grid1.refreshView();
          } else {
            console.error("返回的数据无效或为空:", data);
          }
        } catch (error) {
          console.error("处理数据时出错:", error);
        }
      })
      .catch((error) => {
        console.error("打开NGHelp时发生错误:", error);
      });
  }

  //////////////////////////////////////////////////mstform//////////////////////////////////////////////////

  updateMstformUI();

  //表头字段变化逻辑BEGIN
  useValuesChange(({ args }) => {
    //监听来往单位名称
    console.log(args, "单位名称");
    // mstform.getItem('u_unit_name').getValue()
    console.log(mstform.getItem('u_unit_name').getText());
    
    //监听单位名称
    $NG.execServer(
      "fbsrdxx",
      // { phid: args[0].u_unit_name.origin.compname },
      { compname: `'${mstform.getItem('u_unit_name').getText()}'` },
      function (res) {
        console.log(res);

        const datas = JSON.parse(res.data)[0].extendObjects;
        console.log(datas, "data11111s");
        mstform.getItem("u_zj_no").setValue(datas.cardno)
        mstform.getItem("u_tyshxydm").setValue(datas.unisocialcredit)
        // $NG.updateState((updater) => {
        //   updater.data.p_form_owner_rec_apply_m.setProps({
        //     u_nation: {
        //       value: datas.nation_id,
        //       // label: datas.nationname,
        //     },
        //     u_province: {
        //       value: datas.province_id,
        //       // label: datas.provincename,
        //     },
        //     u_city: {
        //       value: datas.city_id,
        //       // label: datas.cityname,
        //     },
        //     u_region: {
        //       value: datas.region_id,
        //       // label: datas.regionname,
        //     },
        //     u_xxdz: datas.detail_add,
        //   });
        // });
        if (datas.region_id) {
          console.log(datas.region_id, "datas.region_id");
          $NG.execServer("getAddressToId", { phid: datas.region_id }, function (res2) {
            const data2 = JSON.parse(res2.data)[0].extendObjects; //单返回值
            console.log(data2, "data2");
            $NG.updateState((updater) => {
              updater.data.p_form_owner_rec_apply_m.setProps({
                u_nation: {
                  value: data2.nationno,
                  label: data2.nationname,
                },
                u_province: {
                  value: data2.provinceno,
                  label: data2.provincename,
                },
                u_city: {
                  value: data2.cityno,
                  label: data2.cityname,
                },
                u_region: {
                  value: data2.regionno,
                  label: data2.regionname,
                },
                u_xxdz: datas.detail_add,
              });
            });
          });
        }
        //功能扩展
        // $NG.execServer("searchIDBank", { phid: datas.taxbank_id }, function (res1) {
        //   const data = JSON.parse(res1.data)[0].extendObjects; //单返回值
        //   console.log(data, "data");
        //   $NG.updateState((updater) => {
        //     updater.data.p_form_owner_rec_apply_m.setProps({
        //       u_swyh: {
        //         value: data.phid,
        //         label: data.bankno,
        //       }, //税务银行行号11
        //     });
        //   });
        // });

        $NG.updateState((updater) => {
          updater.data.p_form_owner_rec_apply_m.setProps({
            // u_contacts: datas.linkman, //联系人
            // u_contacts_phone: datas.phone, //联系电话
            // u_name1: datas.compname, //
            u_unit_no: args[0].u_unit_name.origin.compno,
            u_id_card: datas.iden_card_id, //法人身份证身份证
            u_nssflx: datas.taxpayertype, //纳税身份类型11
            u_nsr_name: datas.tax_person, //纳税人姓名11

            u_swdjdz: datas.tax_register_addr, //税务地址名称11
            u_swyhmc: datas.taxbank_name, //税务银行名称11
            u_swdjh: datas.taxaccount_no, //税务登记账号11(税务登记账号)
            u_swdjdh: datas.phone, //税务登记电话
            u_tyshxydm: datas.three_to_one, //社会信用代码11(社会信用代码)
            u_zcsj: datas.regdate, //成立日期11
            u_rygm: datas.firm_size, //公司规模11
            // u_yz_name: datas.psn, //法人11()
            u_zczj: datas.reg_fund, //注册资本11
          });
        });
        console.log(datas.taxbank_id, "datas.taxbank_id");
      }
    );
  }, "p_form_owner_rec_apply_m.u_unit_name");
if (mstform.getValues().u_lx == 1) {
  $NG.updateUI((updater) => {
    const fields = ["phid_pc"];
    fields.forEach((field) => {
      updater.fieldSetForm.p_form_owner_rec_apply_m[field].setProps({
        // required: true,
        hidden: true,
      });
    });
  });
}
  useValuesChange(({ args }) => {
    console.log(mstform.getValues().u_lx);
    if (mstform.getValues().u_lx == 2) {
      $NG.updateUI((updater) => {
        const fields = ["phid_pc"];
        fields.forEach((field) => {
          updater.fieldSetForm.p_form_owner_rec_apply_m[field].setProps({
            // required: true,
            hidden: false,
          });
        });
      });
      if (mstform.getValues().phid_pc) {
        return;
      }
      // $NG.alert("请先选择工程项目");
      // mstform.getItem("u_lx").setValue({ code: "", name: "" });
    }else{
      mstform.getItem('phid_pc').setValue('')
      mstform.getItem('u_bussinse').setValue('')
      mstform.getItem('u_sj_name').setValue('')
      mstform.getItem('u_yz_name').setValue('')
      $NG.updateUI((updater) => {
        const fields = ["phid_pc"];
        fields.forEach((field) => {
          updater.fieldSetForm.p_form_owner_rec_apply_m[field].setProps({
            // required: true,
            hidden: true,
          });
        });
      });
    }
  }, "p_form_owner_rec_apply_m.u_lx"); //表头选择u_region字段

  // 监听项目字段变换
  useValuesChange(({ args }) => {
    updateMstformUI();
    if (mstform.getValues().u_lx == 1) {
      return
    }
    console.log(mstform.getValues().u_lx);
    $NG.execServer("getProjectSjhInfo", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
      const datas = JSON.parse(res.data)[0].extendObjects;
      console.log(datas, "getProjectSjhInfo");
      $NG.updateState((updater) => {
        updater.data.p_form_owner_rec_apply_m.setProps({
          u_bussinse: datas.phid, //项目编码
          u_bussinse_EXName: datas.user_sjbm, //项目编码
          u_sj_name: datas.user_sjmc, //项目名称
        });
      });
      //searchYZTosjhsjbm
      if (datas.user_sjbm && datas.user_sjmc) {
        //通过商机编码和名称查询业主名称
        $NG.execServer(
          "YZTosjhsjbm",
          {
            sjname: datas.user_sjmc,
            sjno: datas.user_sjbm,
          },
          function (res) {
            try {
              let YZData = JSON.parse(res.data)[0].extendObjects;
              console.log(YZData, "YZData");
              $NG.updateState((updater) => {
                updater.data.p_form_owner_rec_apply_m.setProps({
                  u_yz_name: YZData.u_yz_name, //业主名称
                });
              });
            } catch (error) { }
          }
        );
      }
    });
    // if (mstform.getValues().u_lx == 2) {
    //   if (mstform.getValues().phid_pc) {
    //     return;
    //   }
    //   $NG.alert("请先选择工程项目");
    //   mstform.getItem("u_lx").setValue({ code: "", name: "" });
    // }
  }, "p_form_owner_rec_apply_m.phid_pc"); //表头选择u_region字段

  useValuesChange(({ args }) => {
    console.log(args[0].u_bussinse.origin.u_opp_name);
    mstform.getItem("u_sj_name").setValue(args[0].u_bussinse.origin.u_opp_name)
    $NG.execServer(
      "YZTosjhsjbm",
      {
        sjname: args[0].u_bussinse.origin.u_opp_name,
        sjno: args[0].u_bussinse.origin.u_opp_no,

      },
      function (res) {
        try {
          let YZData = JSON.parse(res.data)[0].extendObjects;
          console.log(YZData, "YZData");
          $NG.updateState((updater) => {
            updater.data.p_form_owner_rec_apply_m.setProps({
              u_yz_name: YZData.u_yz_name, //业主名称
            });
          });
        } catch (error) { }
      }
    );
  }, "p_form_owner_rec_apply_m.u_bussinse"); //表头选择u_province字段
  useValuesChange(({ args }) => {
    console.log(args.value);
    mstform.getItem("u_region").setValue(""); //表头选择u_product_line字段
    mstform.getItem("u_city").setValue(""); //表头选择u_product_line字段
    $NG.updateUI((updater) => {
      updater.fieldSetForm.p_form_owner_rec_apply_m.u_city.setProps({
        clientSqlFilter: { provinceno: mstform.getValues()?.u_province },
      });
      updater.fieldSetForm.p_form_owner_rec_apply_m.u_region.setProps({
        clientSqlFilter: { cityno: mstform.getValues()?.u_city },
      });
    });
  }, "p_form_owner_rec_apply_m.u_province"); //表头选择u_province字段
  useValuesChange(({ args }) => {
    mstform.getItem("u_region").setValue(""); //表头选择u_product_line字段
    $NG.updateUI((updater) => {
      updater.fieldSetForm.p_form_owner_rec_apply_m.u_city.setProps({
        clientSqlFilter: { provinceno: mstform.getValues()?.u_province },
      });
      updater.fieldSetForm.p_form_owner_rec_apply_m.u_region.setProps({
        clientSqlFilter: { cityno: mstform.getValues()?.u_city },
      });
    });
  }, "p_form_owner_rec_apply_m.u_city"); //表头选择u_city字段
  useValuesChange(({ args }) => {
    console.log(args.value);
    $NG.updateUI((updater) => {
      updater.fieldSetForm.p_form_owner_rec_apply_m.u_city.setProps({
        clientSqlFilter: { provinceno: mstform.getValues()?.u_province },
      });
      updater.fieldSetForm.p_form_owner_rec_apply_m.u_region.setProps({
        clientSqlFilter: { cityno: mstform.getValues()?.u_city },
      });
    });
  }, "p_form_owner_rec_apply_m.u_region"); //表头选择u_region字段
  function initUserType(_data) {
    _data.forEach((item) => {
      item.u_dj_status = '1'
    })
    grid1.refreshView()
  }
  useUpdateRows(({ args }) => {
    const rows = args[0];
    if (page.oType == 'add') {
      rows.forEach((row) => {
        console.log(row, "row");
        if (row.u_wl_no) {
          //功能扩展
          $NG.execServer("getDjxqc", { u_staus: `'定价完成' and 1=1 and itemno = '${row.u_wl_no_EXName}'` }, function (res) {
            if (!res.data || res.count == 0) return; //判断是否有数据
            const parsedData = JSON.parse(res.data);
            const allRecords = parsedData.flatMap(item => item.extendObjects || []);
            if (allRecords.length === 0) {
              console.log("无有效数据");
              return;
            }
            // 获取当前时间戳（用于比较）
            const currentTime = new Date().getTime();

            // 按时间差排序（最接近当前时间的在前）
            const closestRecord = allRecords.reduce((prev, curr) => {
              const prevDiff = Math.abs(new Date(prev.u_date).getTime() - currentTime);
              const currDiff = Math.abs(new Date(curr.u_date).getTime() - currentTime);
              return currDiff < prevDiff ? curr : prev;
            });
            row.u_qty = closestRecord.rest_qty;
            row.u_product_type_mini = closestRecord.u_material_s;
            row.u_item_sort = closestRecord.u_material_m;
            row.u_product_type = closestRecord.u_material_b;
            row.u_zb_prc_vat = closestRecord.u_zb_prc_vat;
            row.u_djprice = closestRecord.u_zb_prc;
            row.u_zb_rate = closestRecord.u_zb_rate;
            row.u_zb_supply = closestRecord.u_zb_supply;
            row.u_djfzr =closestRecord.u_director_phid;
            row.u_djfzr_EXName = closestRecord.u_director_name;
            row.u_dj_dt = closestRecord.dj_dt;
            grid1.refreshView();
          });
          grid1.refreshView();
        }
      });
    }

    if (rows.length > 0 && !mstform.getItem("u_unit_name").getValue() && !mstform.getItem("phid_pc").getValue()) {
      $NG.alert("请先补充项目以及推荐供应商");
      grid1.clearRows(); //先清空明细
      return
      // if () {
      //     $NG.updateUI((updater, state) => {
      //         updater.fieldSetForm.p_form_visa_f_regist_d.u_cnt_name.setProps((e) => ({
      //             ...e,
      //             editor: {
      //                 ...e.editor,
      //                 required: true,
      //                 clientSqlFilter: {
      //                     phid_pc: `${mstform.getItem("phid_pc").getValue()}`,
      //                     bill_type: 1,
      //                 },
      //             },
      //         }));
      //     });
      // }
    }
    // else {
    //   if (args[0].length > 0) {
    //     // $NG.alert("请先补充商机号,推荐供应商");
    //     // grid1.clearRows(); //先清空明细
    //   }
    // }
    initUserType(args[0])
    rows.forEach((row) => {
      //计算损失率
      row.u_ssl = (Number(((Number(row.u_vat_prc) || 0) - (Number(row.u_sc_prc) || 0)) / (Number(row.u_sc_prc) || 0)) || 0).toFixed(4);
      console.log(row.u_wl_name, "row");
      if (row.u_wl_no && mstform.getItem("u_bussinse").getValue() && mstform.getItem("u_dwsx").getValue()) {
        $NG.execServer(
          "getHsdjToYztj",
          {
            "@sjbm": mstform.getItem("u_bussinse").getValue(),
            "@itemno": row.u_wl_no,
            "@dwmc": mstform.getItem("u_dwsx").getValue(),
          },
          function (res) {
            console.log(res, "resgetHsdjToYztj");
          }
        );
      }

      if (row.u_wl_name) {
        //功能扩展
        $NG.execServer("getItemdataphid", { phid: row.u_wl_name }, function (res) {
          if (!res.data || res.count == 0) return; //判断是否有数据
          const data = JSON.parse(res.data)[0].extendObjects; //单返回值
          $NG.execServer("getItemdataByPhid", { phid: data.phid_itemdata }, function (res) {
            const datas = JSON.parse(res.data)[0].extendObjects; //单返回值
            row.u_gg = datas.spec;
            row.u_jldw = datas.msunit_name;
            row.u_wl_no = datas.itemno;
            console.log(datas); //物料小类
            console.log(datas.phid_resbs); //物料小类
          });
        });
        $NG.execServer("getResKSeach", { item_phid: row.u_wl_name }).then(
          (res) => {
            if (!res.data || res.count == 0) return; //判断是否有数据
            const data = JSON.parse(res.data)[0].extendObjects; //单返回值
            console.log(data.hsprc, "data.hsprc");
            if (data.hsprc === 0) {
              console.error("市场价格不能为 0，否则会导致除数为 0 的错误。");
            } else {
              row.u_sc_prc = data.hsprc;
            }
            let result = calculateLossRate(row.u_vat_prc, row.u_sc_prc);
            console.log(result, "11111");
            row.u_ssl = result;
            grid1.refreshView();
          },
          (error) => {
            console.log(error);
          }
        );
      }
      // 根据物料编码带出信息
      if (row.u_wl_no_EXName) {
        $NG.execServer("getItemdataByNo", { itemno: "'" + row.u_wl_no_EXName + "'" }, function (res) {
          if (res.count > 0) {
            let requestData = JSON.parse(res.data)[0].extendObjects; //单返回值
            console.log(requestData, "获取请求值");
            //物料名称
            row.u_wl_name = requestData.itemname;
            //物料编码
            row.u_wl_no = requestData.phid;
            row.u_wl_no_EXName = requestData.itemno;
            //规格
            row.u_gg = requestData.spec;
            //计量单位
            row.u_jldw = requestData.msunit_name;
            // row.u_jldw = requestData.msunit_phid;
            // row.u_jldw_EXName = requestData.msunit_name; //单位
            //物料分类
            row.u_product_type_mini = requestData.phid_resbs; //单位
            row.u_product_type_mini_EXName = requestData.name; //单位
            if (row.u_product_type_mini) {
              $NG.execServer("getAutoType", { phid: row.u_product_type_mini }, function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects; //单返回值
                row.u_item_sort = datas.f_phid;
                row.u_item_sort_EXName = datas.fname;
                row.u_product_type = datas.g_phid;
                row.u_product_type_EXName = datas.gname;
                // row.u_product_type_mini = datas.phid_resbs;
                // row.u_product_type_mini_EXName = datas.name;
                grid1.refreshView();
              });
            }
            grid1.refreshView();
          } else {
            console.log("useUpdateRows没有找到拟采购清单"); // items.u_u_pur_item = null; // items.u_u_pur_item_EXName = null;
          }
        });
      }
      // if (row.u_product_type_mini) {
      //   console.log('2222333333333333');

      //   $NG.execServer("getAutoType", { phid: row.u_product_type_mini }, function (res) {
      //     const datas = JSON.parse(res.data)[0].extendObjects; //单返回值
      //     console.log(datas,'22222222222222222222222222');

      //     row.u_item_sort = datas.f_phid;
      //     row.u_item_sort_EXName = datas.fname;
      //     row.u_product_type = datas.g_phid;
      //     row.u_product_type_EXName = datas.gname;
      //     row.u_product_type_mini = datas.phid_resbs;
      //     row.u_product_type_mini_EXName = datas.name;
      //     grid1.refreshView();
      //   });
      // }
      grid1.refreshView();
    });
  }, "p_form_owner_rec_apply_d1");
  //页面条件
  if (page.oType == "add") {
    mstform.getItem("ng_insert_dt").setValue(new Date());
  }

  function updateMstformUI() {
    if (mstform.getValues().phid_pc) {
      $NG.updateUI((updater) => {
        const fields = ["u_tjr"];
        fields.forEach((field) => {
          // $NG.getPageUI();
          // 根据组件目录设置路径，可能存在
          // fieldSetForm
          // PCFieldSetPanelGroup[i][field]
          updater.fieldSetForm.p_form_owner_rec_apply_m.PCFieldSetPanelGroup1[field].setProps({
            // hidden: true, //隐藏
            // required: true, //必输
            // disabled: true, //只读
            clientSqlFilter: `m.phid_pc = ${mstform.getItem("phid_pc").getValue() || ""}`,
            //  "c_no in ('1','2','3','4')",
            // placeholder: "请选择", //输入框字段加提示语
            // data: [{ value: "01", label: "实施外包用工" }], //下拉过滤
          });
        });
      });
    }
  }
});
function calculateLossRate(taxIncludedPrice = 0, marketPrice) {
  let lossRate = (Number(taxIncludedPrice) - Number(marketPrice)) / Number(marketPrice);
  return lossRate;
}
